﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Globalization;

namespace BPMS.Utility
{
    public class UnicodeHelper
    {
        /// <summary>
        /// 中文转换为Unicode字符
        /// </summary>
        /// <param name="strChan">中文</param>
        /// <returns></returns>
        public static string ChaneseToUnicode(string strChan)
        {
            StringBuilder sbResult = new StringBuilder();
            if (string.IsNullOrEmpty(strChan))
            {
                return sbResult.ToString();
            }
            foreach (char cha in strChan)
            {
                if (Regex.IsMatch(cha.ToString(), @"^[\u4e00-\u9fa5]"))
                {
                    sbResult.Append("\\u" + ((int)cha).ToString("x"));
                }
                else
                {
                    sbResult.Append(cha.ToString());
                }
            }
            return sbResult.ToString();
        }
        /// <summary>
        /// Unicode字符转换为中文
        /// </summary>
        /// <param name="strUni">Unicode字符</param>
        /// <returns></returns>
        public static string UnicodeToChanese(string strUni)
        {
            Regex reg = new Regex(@"(?i)\\u([0-9a-f]{4})");
            string strResult = reg.Replace(strUni, delegate(Match match)
            {
                return ((char)int.Parse(match.Groups[1].Value, NumberStyles.HexNumber)).ToString();
            });
            return strResult;
        }
    }
}
